package com.cyzy.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    //保存sqlSessionFactory
    private static SqlSessionFactory sqlSessionFactory;

    //防止外部实例化
    private MybatisUtil(){}

    static {
        try {
            //读取Mybatis配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //获取sqlSessionFactory
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

    //获取SqlSession
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }

}
